package com.example.myapplication16_2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyServer {
    // 端口号
    private static final int PORT = 9999;
    // 线程池
    private static ExecutorService executorService = Executors.newCachedThreadPool();
    // 保存所有客户端连接
    private static List<Socket> clientList = new ArrayList<>();

    public static void main(String[] args) {
        try {
            // 创建服务器Socket
            ServerSocket serverSocket = new ServerSocket(PORT);
            System.out.println("服务器已启动，等待客户端连接...");

            while (true) {
                // 接收客户端连接
                Socket client = serverSocket.accept();
                System.out.println("客户端已连接: " + client.getInetAddress().getHostAddress());

                // 将新连接的客户端加入列表
                clientList.add(client);

                // 为每个客户端创建一个线程处理消息
                executorService.execute(new ClientHandler(client));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 客户端处理线程
    static class ClientHandler implements Runnable {
        private Socket socket;
        private BufferedReader reader;
        private PrintWriter writer;

        public ClientHandler(Socket socket) {
            this.socket = socket;
            try {
                // 创建输入流，明确使用UTF-8编码
                reader = new BufferedReader(
                        new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
                // 创建输出流，明确使用UTF-8编码
                writer = new PrintWriter(
                        new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8), true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            String message;
            try {
                // 循环读取客户端发送的消息
                while ((message = reader.readLine()) != null) {
                    System.out.println("收到消息: " + message);
                    // 将消息群发给所有客户端
                    broadcastMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 当客户端断开连接时，从列表中移除
                try {
                    clientList.remove(socket);
                    if (reader != null) reader.close();
                    if (writer != null) writer.close();
                    if (socket != null) socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // 群发消息方法
        private void broadcastMessage(String message) {
            // 遍历所有客户端，发送消息
            for (Socket client : clientList) {
                try {
                    // 使用UTF-8编码发送消息
                    PrintWriter out = new PrintWriter(
                            new OutputStreamWriter(client.getOutputStream(), StandardCharsets.UTF_8), true);
                    out.println(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
} 